package mongo.db.clients.firsts;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class MultiplyMain {

	public static void main(String[] args) throws IOException {

		try {
			MongoClient client = new MongoClient("202.191.136.234", 27017);
			DB db = client.getDB("netflowdb");
			DBCollection collection = db.getCollection("netflow_column_list");
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}

		// System.out.println(readIpsFromFile());

		List<String> routerIps = null;
		routerIps = Arrays.asList(readIpsFromFile().split("\n"));

		for (String routerIp : routerIps) {

		}

		// System.exit(1);

		ExecutorService routerExeService = Executors.newFixedThreadPool(100);

		List<Future<Integer>> futureList = new ArrayList<Future<Integer>>();

		for (String routerip : routerIps) {
			Multiply threadObj = new Multiply(routerip);
			futureList.add(routerExeService.submit(threadObj));
		}

		try {
			for (Future<Integer> future : futureList) {
				future.get();
			}
		} catch (Exception e) {
			System.out.println("Aggregator : " + e);
		}

		Date endTime = new Date();

		System.out.println("jobs successfully completed : " + futureList.size());
		futureList.clear();
		System.out.println("executor service shutting down....");
		routerExeService.shutdown();
	}

	private static String readIpsFromFile() throws IOException {
		StringBuilder stringBuilder = null;
		try {
			String fileName = "/tmp/iplist.txt";
			BufferedReader reader = new BufferedReader(new FileReader(fileName));
			String line = null;
			stringBuilder = new StringBuilder();
			String ls = System.getProperty("line.separator");

			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
				stringBuilder.append(ls);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return stringBuilder.toString();
	}

}
